package com.copa.security;

import com.copa.constant.ResponseConstant;
import com.copa.constant.RoleConstant;
import com.copa.domain.ResponseDto;
import com.copa.module.user.domain.entity.CustomerUserEntity;
import com.copa.module.user.domain.entity.UserEntity;
import com.copa.module.user.manage.UserRoleManage;
import com.copa.module.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author copa
 * @createDate 2021-01-05 11:38
 * @function 登录验证
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleManage userRoleManage;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ResponseDto<UserEntity> userRes = userService.findByUsername(username);
        if (userRes.getCode() == ResponseConstant.STATUS_FAIL) {
            // 不存在该用户
            throw new UsernameNotFoundException("该用户不存在！");
        }

        ResponseDto<List<Long>> roleIdsRes = userRoleManage.listRoleByUserIdAndRoleId(userRes.getData().getId(), RoleConstant.ADMIN.longValue());

        if (roleIdsRes.getCode() == ResponseConstant.STATUS_FAIL) {
            // 没有管理员权限
            throw new UsernameNotFoundException("该用户权限不足！");
        }

        // 登录成功
        List<GrantedAuthority> authorities = new ArrayList<>();

        UserEntity user = userRes.getData();

        authorities.add(new SimpleGrantedAuthority("manage"));

        CustomerUserEntity customerUser = CustomerUserEntity.builder()
                .user(user)
                // 将该权限添加到security
                .authorities(authorities)
                .build();

        return customerUser;
    }
}
